package top.kaoshanji.p3ch14a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 代码清单-p3ch14a-247页a：发送进程更新的异步Servlet
 * URL访问地址：/asyncComplete
 * 这个在 web.xml 文件里配置
 * @author kaoshanji
 * ^_^
 * create time 2025/4/9 15:54
 */
public class AsyncCompleteServlet extends HttpServlet {

    private static final long serialVersionUID = 78234L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_HTML.toString());
        final PrintWriter writer = resp.getWriter();

        writer.println("<html><head><title>Async Servlet</title></head>");
        writer.println("<body><div id='progress'></div>");

        final AsyncContext asyncContext = req.startAsync();
        asyncContext.setTimeout(60000);
        asyncContext.start(new Runnable() {

            @Override
            public void run() {
                System.out.println("new thread: " + Thread.currentThread());
                for (int i = 0; i < 10; i ++) {
                    writer.println("<script>");
                    writer.println("document.getElementById(" +
                            "'progress').innerHTML = '" +
                            (i * 10) + "% complete'");
                    writer.println("</script>");

                    writer.flush();

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        /// //
                    }

                }

                writer.println("<script>");
                writer.println("document.getElementById(" +
                        "'progress').innerHTML = 'DONE'");
                writer.println("</script>");
                writer.println("</body></html>");

                asyncContext.complete();
            }
        });

    }

}
